import Vue from 'vue'
import FastClick from 'fastclick'
import VueRouter from 'vue-router'
import App from './App'
import './data/adaptive' //rem适配

// import TestPreview from './components/TestPreview'

// window.addEventListener('resize', util)


import Vuex from 'vuex'
Vue.use(Vuex)

Vue.use(VueRouter)

import { SlideGifPlugin, ClockPlugin, WechatPlugin, DatetimePlugin, DevicePlugin, BusPlugin, AlertPlugin, ToastPlugin, ConfirmPlugin } from 'vux'
Vue.use(AlertPlugin)
Vue.use(DevicePlugin)
Vue.use(DatetimePlugin)
Vue.use(ConfirmPlugin)
Vue.use(ToastPlugin)
Vue.use(WechatPlugin)
Vue.use(BusPlugin)
Vue.use(SlideGifPlugin)
Vue.use(ClockPlugin)

import { XSwitch } from 'vux'
Vue.use(XSwitch)
import vuexI18n from 'vuex-i18n'

require('es6-promise').polyfill()

import VueResource from 'vue-resource';
Vue.use(VueResource);

import store from './store/store';
Vue.use(vuexI18n.plugin, store)

import routes from './routers';
import api from './api';
import VueSocketio from 'vue-socket.io';
Vue.use(VueSocketio, api.globalUrl);
var version = "4.0.4";
store.commit({ type: "setValue", "version": version });

// const wx = Vue.wechat
// const http = Vue.http

// console.log("wechat", Vue.device.isWechat);


// url路由跳转. 全局function
Vue.prototype.go = function(path) {
  router.push(`/${path}`)
}
Vue.prototype.version = { ver: version, get: true }
Vue.prototype.app = { title: "时间清单" }
Vue.prototype.showVersion = function() {
  // if (!Vue.prototype.version.get) {
  //     Vue.prototype.version.get = true;
  //     router.push(`/`)
  // }
}
Vue.prototype.setTitle = function(title) {
  // if (!Vue.prototype.is_weixin()) {
  //   return;
  // }
  var body = document.getElementsByTagName('body')[0];
  document.title = title;
  var iframe = document.createElement("iframe");
  iframe.style.display = "none";
  iframe.setAttribute("src", "https://cdns.7dtime.com/favicon.ico");
  var d = function() {
    setTimeout(function() {
      iframe.removeEventListener('load', d);
      document.body.removeChild(iframe);
    }, 0);
  };
  iframe.addEventListener('load', d);
  document.body.appendChild(iframe);
}

Vue.prototype.is_weibo = function() {
  var ua = navigator.userAgent.toLowerCase();
  return ua.match(/WeiBo/i) == "weibo";
}
Vue.prototype.is_weixin = function() {
  var ua = navigator.userAgent.toLowerCase();
  return ua.match(/MicroMessenger/i) == "micromessenger";
  //if (ua.match(/MicroMessenger/i) == "micromessenger")return true;
  //return false;
}
Vue.prototype.isMob = function(value) {
  return regBox.regMobile.test(value);
}
Vue.prototype.isEmail = function(value) {
  // /^((\+?86)|(\(\+86\)))?(13[012356789][0-9]{8}|15[012356789][0-9]{8}|18[02356789][0-9]{8}|147[0-9]{8}|1349[0-9]{7})$/;
  return regBox.regEmail.test(value);
}
var regBox = {
  regEmail: /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/, //邮箱
  regMobile: /^0?1[3|4|5|7|8|9][0-9]\d{8}$/, //手机
  regTel: /^0[\d]{2,3}-[\d]{7,8}$/ //电话
}
Vue.prototype.tongji = function(category, action, label, value) {
  window.ga && window.ga('send', 'event', category, action, label || "", value || "");
  window._hmt && window._hmt.push(['_trackEvent', category, action, label || "", value || ""])
}
Vue.prototype.tongji("app", "run", "version", version);
Vue.prototype.GetRequest = function() {   
  var url = window.location.href; //获取url中"?"符后的字串
  var theRequest = new Object();
  var index = url.indexOf("?");
  if (index != -1) {
    url = url.substr(index);
    var index1 = url.indexOf("#");
    if (index1 > 0) {
      url = url.substr(0, index1);
    }
    var str = url.substr(1);
    var strs = str.split("&");
    for (var i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
    }
  }
  return theRequest;
}
Vue.prototype.appTitle = "7dtime";
const router = new VueRouter({
  routes
})

import ga from 'vue-ga'
import ba from 'vue-ba'
if (process.env.NODE_ENV != "development") { //dev.7dtime.com开发统计
  ga(router, 'UA-40324677-6');
  Vue.use(ba, '0ea90a88c8bf02ff94aa301a276ff886')
} else { //7dtime.com 时间清单正式服
  Vue.use(ba, 'eee3e11d38889522643bfe1bb9f343f9') //统计开发数据
}


const history = window.sessionStorage
history.clear()
let historyCount = history.getItem('count') * 1 || 0
history.setItem('/', 0)

router.beforeEach(function(to, from, next) {
  store.commit('updateLoadingStatus', { isLoading: true })
  const toIndex = history.getItem(to.path)
  const fromIndex = history.getItem(from.path)

  if (toIndex) {
    if (!fromIndex || parseInt(toIndex, 10) > parseInt(fromIndex, 10) || (toIndex === '0' && fromIndex === '0')) {
      store.commit('updateDirection', { direction: 'forward' })
    } else {
      store.commit('updateDirection', { direction: 'reverse' })
    }
  } else {
    ++historyCount
    history.setItem('count', historyCount)
    to.path !== '/' && history.setItem(to.path, historyCount)
    store.commit('updateDirection', { direction: 'forward' })
  }

  if (/\/http/.test(to.path)) {
    let url = to.path.split('http')[1]
    window.location.href = `http${url}`
  } else {
    next()
  }
})

var lastPath;
router.afterEach(function(to) {
  console.log("path:", to.fullPath);
  var path = to.fullPath.substr(1); //去除第一个 /符号
  var index = path.indexOf("/");
  if (index != -1) {
    var main = "/" + path.substring(0, index);
    localStorage.setItem(main, to.fullPath);
  }
  store.commit('updateLoadingStatus', { isLoading: false });
  ba.trackPageview(to.fullPath);

  try { doAllShare({ type: "router", pathH5: to.fullPath }) } catch (e) {} //html中代码
  // checkAddPath(to.fullPath);
  // lastPath = to.fullPath;
})

function checkAddPath(path) {
  if (lastPath != null) return; //如果已经访问过
  if (path == "/" || path.indexOf("/m_") == 0) return; // 如果是主页
  if (path.indexOf("/n_") == 0) return; //如果是启动页
  console.log("checkAddPath", path)
  router.push("/m_mine");
  // router.push(path);
  // setTimeout(() => { router.push("/") }, 1);
  setTimeout(() => { router.push(path) }, 1000);
}

localStorage.removeItem("importTime");

FastClick.attach(document.body)

Vue.config.productionTip = false

/* eslint-disable no-new */
window.app = new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app-box')
